// Global vars
var ProfilDataStore;
var ProfilColumnModel;
var ProfilListingEditorGrid;
var ProfilCreateForm;
var ProfilCreateWindow;

var PrezimeField;
var ImeField;
var EmailField;
var UsernameField;
var PasswordField;
var PolField;
var AdresaField;
var TelefonField;
var MobilniField;
var TipField;
var SkolaField;

direktor_grid = function(options) {

  Ext.QuickTips.init();

  // This saves the Profil after a cell has been edited
  function saveTheProfil(oGrid_event){
   Ext.Ajax.request({
      waitMsg: 'Please wait...',
      url: '/administracija.php/direktor/grid/skola_id/' + options.skola_id,
      params: {
         task: "UPDATEPRES",
         IDprofil: oGrid_event.record.data.IDprofil,
         prezime: oGrid_event.record.data.Prezime,
         ime: oGrid_event.record.data.Ime,
         email: oGrid_event.record.data.Email,
         username: oGrid_event.record.data.Username,
         password: oGrid_event.record.data.Password,
         pol: oGrid_event.record.data.Pol,
         adresa: oGrid_event.record.data.Adresa,
         telefon: oGrid_event.record.data.Telefon,
         mobilni: oGrid_event.record.data.Mobilni,
         tip: oGrid_event.record.data.Tip,
         skola: oGrid_event.record.data.Skola
      },
      success: function(response){
         var result=eval(response.responseText);
         switch(result){
         case 1:
            ProfilDataStore.commitChanges();
            ProfilDataStore.reload();
            break;
         default:
            Ext.MessageBox.alert(options.greska_naslov,options.greska_save);
            break;
         }
      },
      failure: function(response){
         var result=response.responseText;
         Ext.MessageBox.alert(options.greska, options.greska_baza);
      }
   });
  }

  // this creates a new Profil
  function createTheProfil(){
     if(isProfilFormValid()){
      Ext.Ajax.request({
        waitMsg: options.cekaj,
        url: '/administracija.php/direktor/grid/skola_id/' + options.skola_id,
        params: {
          task: "CREATEPRES",
          prezime:  PrezimeField.getValue(),
          ime:      ImeField.getValue(),
          email:    EmailField.getValue(),
          username:    UsernameField.getValue(),
          password:    PasswordField.getValue(),
          pol:    PolField.getValue(),
          adresa:    AdresaField.getValue(),
          telefon:    TelefonField.getValue(),
          mobilni:  MobilniField.getValue(),
          tip:    TipField.getValue(),
          skola:  SkolaField.getValue()
        },
        success: function(response){
          var result=eval(response.responseText);
          switch(result){
          case 1:
            Ext.MessageBox.alert(options.ok_napravljen,options.napravljen_text);
            ProfilDataStore.reload();
            ProfilCreateWindow.hide();
            break;
          default:
            Ext.MessageBox.alert(options.upozorenje,options.greska_napravi);
            break;
          }
        },
        failure: function(response){
          var result=response.responseText;
          Ext.MessageBox.alert(options.greska,options.greska_baza);
        }
      });
    } else {
      Ext.MessageBox.alert(options.upozorenje, options.invalid_form);
    }
  }

  // reset the Form before opening it
  function resetProfilForm(){
    PrezimeField.setValue('');
    ImeField.setValue('');
    EmailField.setValue('');
    UsernameField.setValue('');
    PasswordField.setValue('');
    PolField.setValue(null);
    AdresaField.setValue('');
    TelefonField.setValue('');
    MobilniField.setValue('');
    TipField.setValue(null);
    SkolaField.setValue(SkolaDataStore.data.items[0].data.id);
  }

  // check if the form is valid
  function isProfilFormValid(){
      return(PrezimeField.isValid() && ImeField.isValid() && EmailField.isValid() && UsernameField.isValid() && PasswordField.isValid() && PolField.isValid() && AdresaField.isValid() && TelefonField.isValid() && MobilniField.isValid() && TipField.isValid() && SkolaField.isValid());
  }

  // display or bring forth the form
  function displayFormWindow(){
     if(!ProfilCreateWindow.isVisible()){
       resetProfilForm();
       ProfilCreateWindow.show();
     } else {
       ProfilCreateWindow.toFront();
     }
  }

  function confirmDeleteProfil(){
    if(ProfilListingEditorGrid.selModel.getCount() == 1) // only one Profil is selected here
    {
      Ext.MessageBox.confirm(options.potvrda,options.potvrda_brisi, deleteProfil);
    } else if(ProfilListingEditorGrid.selModel.getCount() > 1){
      Ext.MessageBox.confirm(options.potvrda,options.potvrda_brisi_vise, deleteProfil);
    } else {
      Ext.MessageBox.alert(options.greska_naslov,options.brisi_nista);
    }
  }

  function deleteProfil(btn){
    if(btn=='yes'){
         var selections = ProfilListingEditorGrid.selModel.getSelections();
         var prez = [];
         for(i = 0; i< ProfilListingEditorGrid.selModel.getCount(); i++){
          prez.push(selections[i].json.IDprofil);
         }
         var encoded_array = Ext.encode(prez);
         Ext.Ajax.request({
            waitMsg: options.cekaj,
            url: '/administracija.php/direktor/grid/skola_id/' + options.skola_id,
            params: {
               task: "DELETEPRES",
               ids:  encoded_array
              },
            success: function(response){
              var result=eval(response.responseText);
              switch(result){
              case 1:  // Success : simply reload
                ProfilDataStore.reload();
                break;
              default:
                Ext.MessageBox.alert(options.upozorenje,options.delete_sve);
                break;
              }
            },
            failure: function(response){
              var result=response.responseText;
              Ext.MessageBox.alert(options.greska,options.greska_baza);
              }
         });
      }
  }

  function startAdvancedSearch(){
      // local vars
      var ProfilSearchForm;
      var ProfilSearchWindow;
      var SearchImeItem;
      var SearchPrezimeItem;

     function listSearch(){
         // render according to a SQL date format.

         // change the store parameters
        ProfilDataStore.baseParams = {
         task: 'SEARCH',
         ime: SearchImeItem.getValue(),
         prezime : SearchPrezimeItem.getValue()
       };
         // Cause the datastore to do another query :
       ProfilDataStore.reload({params: {start: 0, limit: 30}});
     }

     function resetSearch(){
         // reset the store parameters
        ProfilDataStore.baseParams = {
         task: 'LISTING'
       };
         // Cause the datastore to do another query :
       ProfilDataStore.reload({params: {start: 0, limit: 30}});
         ProfilSearchWindow.close();
     }

      SearchImeItem = new Ext.form.TextField({
          fieldLabel: options.ime,
          maxLength: 20,
          anchor : '95%'
            });

      SearchPrezimeItem = new Ext.form.TextField({
          fieldLabel: options.prezime,
          maxLength: 20,
          anchor : '95%'
            });

      ProfilSearchForm = new Ext.FormPanel({
       //labelAlign: 'top',
       bodyStyle: 'padding: 5px',
       width: 300,
       items: [{
         layout: 'form',
         border: false,
         items: [ SearchPrezimeItem, SearchImeItem ],
         buttons: [{
               text: options.trazi,
               handler: listSearch
             },{
               text: options.zatvori,
               handler: resetSearch
             }]
         }]
     });

     ProfilSearchWindow = new Ext.Window({
         title: options.trazi_profil,
         closable:true,
         width: 200,
         height: 400,
         plain:true,
         layout: 'fit',
         items: ProfilSearchForm
     });


     // once all is done, show the search window
     ProfilSearchWindow.show();
  }

  function onProfilListingEditorGridContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    var coords = e.getXY();
    ProfilListingContextMenu.rowRecord = grid.store.getAt(rowIndex);
    grid.selModel.selectRow(rowIndex);
    ProfilListingSelectedRow=rowIndex;
    ProfilListingContextMenu.showAt([coords[0], coords[1]]);
  }

  function modifyProfilContextMenu(){
      ProfilListingEditorGrid.startEditing(ProfilListingSelectedRow,1);
  }

  function deleteProfilContextMenu(){
      confirmDeleteProfil();
  }

  // << CONFIG >>
  ProfilDataStore = new Ext.data.Store({
      id: 'AdresarDataStore',
      proxy: new Ext.data.HttpProxy({
                url: '/administracija.php/direktor/grid/skola_id/' + options.skola_id,
                method: 'POST'
            }),
            baseParams:{task: "LISTING"}, // this parameter is passed for any HTTP request
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[
        {name: 'IDprofil', type: 'int', mapping: 'IDprofil'},
        {name: 'Prezime', type: 'string', mapping: 'prezime'},
        {name: 'Ime', type: 'string', mapping: 'ime'},
        {name: 'Email', type: 'string', mapping: 'email'},
        {name: 'Username', type: 'string', mapping: 'username'},
        {name: 'Password', type: 'string', mapping: 'password'},
        {name: 'Pol', type: 'int', mapping: 'pol'},
        {name: 'Adresa', type: 'string', mapping: 'adresa'},
        {name: 'Telefon', type: 'string', mapping: 'telefon'},
        {name: 'Mobilni', type: 'string', mapping: 'mobilni'},
        {name: 'Tip', type: 'string', mapping: 'tip'},
        {name: 'Skola', type: 'string', mapping: 'skola'}
      ])
    });

  PolDataStore = new Ext.data.SimpleStore({
                fields:['polValue', 'polName'],
                data: [[1,options.musko],[0,options.zensko]]
                });

  TipDataStore = new Ext.data.JsonStore({
                  autoLoad: true,
                  url: '/administracija.php/grid/tip/tip/direktor',
                  root: 'rows',
                  fields:['id', 'naziv']
              });

  SkolaDataStore = new Ext.data.JsonStore({
                  autoLoad: true,
                  url: '/administracija.php/grid/skola',
                  root: 'rows',
                  fields:['id', 'naziv']
              });


  ProfilColumnModel = new Ext.grid.ColumnModel(
    [{
        header: options.prezime,
        dataIndex: 'Prezime',
        sortable: true,
        width: 80,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 30
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.ime,
        dataIndex: 'Ime',
        sortable: true,
        width: 80,
        editor: new Ext.form.TextField({
            allowBlank: false,
            maxLength: 30
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },{
        header: options.email,
        dataIndex: 'Email',
        sortable: true,
        width: 100,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 45
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.username,
        dataIndex: 'Username',
        sortable: true,
        width: 60,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 45
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.password,
        dataIndex: 'Password',
        sortable: true,
        width: 60,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 45
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.pol,
        dataIndex: 'Pol',
        sortable: true,
        width: 35,
        editor: new Ext.form.ComboBox({
             typeAhead: true,
             triggerAction: 'all',
             store:PolDataStore,
             mode: 'local',
             displayField: 'polName',
             valueField: 'polValue',
             listClass: 'x-combo-list-small'
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return (value== 1) ? options.musko : options.zensko;
        }
      },
      {
        header: options.adresa,
        dataIndex: 'Adresa',
        sortable: true,
        width: 100,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 45
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.telefon,
        dataIndex: 'Telefon',
        sortable: true,
        width: 60,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 45
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
        header: options.mobilni,
        dataIndex: 'Mobilni',
        sortable: true,
        width: 80,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 15
          }),
        renderer: function(value, cell){
         cell.css = "coolcell";
         return value;
        }
      },
      {
          header: options.tip,
          dataIndex: 'Tip',
          width: 80,
          renderer: function(value, cell){
            cell.css = "coolcell";
            if(value)
              return value;
            else
              return '';
            },
          editor: new Ext.form.ComboBox({
              triggerAction: 'all',
              name: 'tip',
              mode: 'local',
              lazyInit: true,
              displayField: 'naziv',
              valueField: 'id',
              forceSelection: true,
              typeAhead: true,
              inputType:'text',
              fieldLabel: options.tip,
              store: TipDataStore
          })

      },
      {
          header: options.skola,
          dataIndex: 'Skola',
          width: 80,
          renderer: function(value, cell){
            cell.css = "coolcell";
            return value;
            },
          editor: new Ext.form.ComboBox({
              triggerAction: 'all',
              name: 'skola',
              mode: 'local',
              lazyInit: true,
              displayField: 'naziv',
              valueField: 'id',
              forceSelection: true,
              typeAhead: true,
              inputType:'text',
              fieldLabel: options.skola,
              store: SkolaDataStore
          })

      }
      ]
    );

   ProfilListingEditorGrid =  new Ext.grid.EditorGridPanel({
      id: 'ProfilListingEditorGrid',
      renderTo   : Ext.get('grid_content'),
      width: 850,
      height:780,
      store: ProfilDataStore,
      cm: ProfilColumnModel,
      enableColLock:false,
      clicksToEdit:1,
      selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
      bbar: new Ext.PagingToolbar({
                pageSize: 30,
                store: ProfilDataStore,
                displayInfo: true
            }),
      tbar: [
          {
            text: options.dodaj_profil,
            width: 20,
            tooltip: options.dodaj_profil_tt,
            iconCls:'add',                      // reference to our css
            handler: displayFormWindow
          }, '-', {
            text: options.brisi_odabrane,
            tooltip: options.brisi_odabrane_tt,
            handler: confirmDeleteProfil,   // Confirm before deleting
            iconCls:'add'
          }, '-', {
            text: options.adv_pretraga,
            tooltip: options.adv_pretraga_tt,
            handler: startAdvancedSearch,
            iconCls:'add'
          }, '-', new Ext.app.SearchField({
                    id: 'searchfield',
                    store: ProfilDataStore,
            params: {start: 0, limit: 30},
                    width: 120
        })
      ]
    });
  ProfilListingEditorGrid.addListener('rowcontextmenu', onProfilListingEditorGridContextMenu);

  ProfilListingContextMenu = new Ext.menu.Menu({
      id: 'ProfilListingEditorGridContextMenu',
      items: [
      { text: options.cont_modify, handler: modifyProfilContextMenu },
      { text: options.cont_delete, handler: deleteProfilContextMenu }
      ]
   });

  ProfilDataStore.load({params: {start: 0, limit: 30}});
  ProfilListingEditorGrid.on('afteredit', saveTheProfil);

  PrezimeField = new Ext.form.TextField({
    id: 'PrezimeField',
    fieldLabel: options.prezime,
    maxLength: 20,
    allowBlank: false,
    anchor : '95%'
      });

  ImeField = new Ext.form.TextField({
    id: 'ImeField',
    fieldLabel: options.ime,
    maxLength: 20,
    allowBlank: false,
    anchor : '95%'
      });

  EmailField = new Ext.form.TextField({
    id:'EmailField',
    fieldLabel: options.email,
    maxLength: 45,
    allowBlank: true,
    anchor : '95%'
    });

  UsernameField = new Ext.form.TextField({
    id:'UsernameField',
    fieldLabel: options.username,
    maxLength: 45,
    allowBlank: true,
    anchor : '95%'
    });

  PasswordField = new Ext.form.TextField({
    id:'PasswordField',
    fieldLabel: options.password,
    maxLength: 45,
    allowBlank: true,
    anchor : '95%'
    });

 PolField = new Ext.form.ComboBox({
    id:'PolField',
    fieldLabel: options.pol,
    typeAhead: true,
    forceSelection: true,
    triggerAction: 'all',
    cls: 'grid_combo',
    store: PolDataStore,
    mode: 'local',
    displayField: 'polName',
    valueField: 'polValue',
    listClass: 'x-combo-list-small'
    });

  AdresaField = new Ext.form.TextField({
    id:'AdresaField',
    fieldLabel: options.adresa,
    maxLength: 45,
    allowBlank: true,
    anchor : '95%'
    });

  TelefonField = new Ext.form.TextField({
    id:'TelefonField',
    fieldLabel: options.telefon,
    maxLength: 45,
    allowBlank: true,
    anchor : '95%'
    });

  MobilniField = new Ext.form.TextField({
    id:'MobilniField',
    fieldLabel: options.mobilni,
    maxLength: 20,
    allowBlank: true,
    anchor : '95%'
    });

  TipField = new Ext.form.ComboBox({
             id:'TipField',
             fieldLabel: options.tip,
             triggerAction: 'all',
             name: 'tip',
             mode: 'local',
             lazyInit: true,
             displayField: 'naziv',
             valueField: 'id',
             forceSelection: false,
             typeAhead: true,
             inputType:'text',
             fieldLabel: options.tip,
             store: TipDataStore
    });

  SkolaField = new Ext.form.ComboBox({
             id:'SkolaField',
             fieldLabel: options.skola,
             triggerAction: 'all',
             name: 'skola',
             mode: 'local',
             lazyInit: true,
             displayField: 'naziv',
             valueField: 'id',
             forceSelection: true,
             typeAhead: true,
             inputType:'text',
             fieldLabel: options.skola,
             store: SkolaDataStore
    });

  ProfilCreateForm = new Ext.FormPanel({
        labelAlign: 'top',
        bodyStyle:'padding:5px',
        width: 600,
        items: [{
            layout:'column',
            border:false,
            items:[{
                columnWidth:0.5,
                layout: 'form',
                border:false,
                items: [PrezimeField, ImeField, EmailField, UsernameField, PasswordField]
            },{
                columnWidth:0.5,
                layout: 'form',
                border:false,
                items: [TipField, SkolaField, MobilniField, TelefonField, AdresaField, PolField]
            }]
        }],
    buttons: [{
      text: options.napravi_pr_btn,
      handler: createTheProfil
    },{
      text: options.otkazi,
      handler: function(){
        // because of the global vars, we can only instantiate one window... so let's just hide it.
        ProfilCreateWindow.hide();
      }
    }]
    });

  ProfilCreateWindow= new Ext.Window({
      id: 'ProfilCreateWindow',
      title: options.napravi_pr_win,
      closable:true,
      width: 610,
      height: 350,
      plain:true,
      layout: 'fit',
      items: ProfilCreateForm
    });

};
